package fun.coding.leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class CombinationSum {

	public static void main(String[] args) {
		int[] a = {2, 3, 6, 7};
		CombinationSum cs = new CombinationSum();
		
		List<List<Integer>> r = cs.combinationSum(a, 7);
		
		for (List<Integer> l : r) {
			for (int i : l) {
				System.out.print(i + ",");
			}
			System.out.println();
		}
	}
	
	public List<List<Integer>> combinationSum(int[] candidates, int target) {
		List<List<Integer>> res = new ArrayList<List<Integer>>();
		List<Integer> sol = new ArrayList<Integer>();
		Arrays.sort(candidates);
		helper(0, candidates, target, res, sol);
		return res;
	}
	
	public void helper(int start, int[] a, int target, List<List<Integer>> res, List<Integer> sol) {
		if (target == 0) {
			res.add(new ArrayList<Integer>(sol));
			return;
		}
		
		for (int i = start; i < a.length; i++) {
			// a is sorted
			if (a[i] > target) break;
			
			if (a[i] <= target) {
				sol.add(a[i]);
				helper(i, a, target - a[i], res, sol);
				sol.remove(sol.size() - 1);
			}
		}
	}

}
